import React, { useEffect } from "react";
import { useSocket } from "@/hooks";
import { useRecoilState } from "recoil";
import { mesh1State } from "@/store";

const TestWs = () => {
  const socket = useSocket();
  let [mesh1, setMesh1] = useRecoilState(mesh1State);

  if (socket) {
    socket.on("message", (data) => {
      console.log("收到message");
      console.log(data);
    });
    socket.on("mesh", (data) => {
      console.log("已经更新顶点数据");
      setMesh1(data);
    });
  }

  const sendMessage = () => {
    if (!socket) return;
    const randomChar = String.fromCharCode(
      Math.floor(Math.random() * 26) + "a".charCodeAt(0),
    );
    console.log(
      "send message",
      randomChar,
      ". Connect status:",
      socket.connected,
    );
    socket.emit("message", randomChar);
  };

  useEffect(() => {
    const interval = setInterval(() => {
      sendMessage();
    }, 5000);

    return () => {
      clearInterval(interval);
    };
  }, [socket]); // 依赖项数组包含 socket

  return (
    <div>
      {/*<p>Random characters are being sent to the server every 3 seconds.</p>*/}
      {/*<p>Check the server console for received messages.</p>*/}
    </div>
  );
};

export default TestWs;
